package cn.mihoyo.tenement.controller;

import cn.mihoyo.base.util.AjaxResult;
import cn.mihoyo.base.util.PageList;
import cn.mihoyo.tenement.domain.Contract;
import cn.mihoyo.tenement.query.ContractQuery;
import cn.mihoyo.tenement.service.ContractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/contract")
public class ContractController {
    @Autowired
    private ContractService contractService;

    @GetMapping
    public List<Contract> findAll(){
        return contractService.findAll();
    }

    @GetMapping("/{id}")
    public Contract findById(@PathVariable("id") Long id){
        return contractService.findById(id);
    }

    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            contractService.delete(id);
            return AjaxResult.me();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.fail();
        }
    }

    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Contract contract){
        try {
            if(contract.getCtId() == null || contract.getCtId() == 0){
                contractService.add(contract);
            }else {
                contractService.update(contract);
            }
            return AjaxResult.me();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.fail();
        }
    }

    @PostMapping
    public PageList queryByPage(@RequestBody ContractQuery query){
        return contractService.queryByPage(query);
    }
}
